 package com.mystery.action;

import com.mystery.pojo.Fitness;
import com.mystery.service.FitnessService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class FitnessAction extends ActionSupport implements ModelDriven<Fitness> {

    private Fitness fitness = new Fitness();

    private List<Fitness> fitnessList;

    public List<Fitness> getFitnessList() {
        return fitnessList;
    }

    public void setFitnessList(List<Fitness> fitnessList) {
        this.fitnessList = fitnessList;
    }

    @Autowired
    private FitnessService fitnessService;

    public String search(){
        HttpServletRequest request = ServletActionContext.getRequest();
        String fitnessName = request.getParameter("fitnessName");
        if("".equals(fitnessName)){
            fitnessList = fitnessService.list();
        }else {
            fitnessList = fitnessService.search("%"+fitnessName+"%");
        }

        return "search";
    }

    public String list(){
        fitnessList = fitnessService.list();
        return "queryAll";
    }

    public String add(){
        HttpServletRequest request = ServletActionContext.getRequest();
        String fitnessId = request.getParameter("fitnessId");
        Fitness fitness = fitnessService.findFitness(fitnessId);
        if(fitness != null){
            ServletActionContext.getRequest().setAttribute("error","已经录入过信息");
            return "add_error";
        }
        String haveClass = ServletActionContext.getRequest().getParameter("haveClass");
        if("是".equals(haveClass)){
            this.fitness.setHaveClass(true);
        }else{
            this.fitness.setHaveClass(false);
        }
        int add = fitnessService.add(this.fitness);
        if( add > 0){
            return "add_ok";
        }
        else {
            ServletActionContext.getRequest().setAttribute("error","对不起录入失败");
            return "add_error";
        }
    }
    @Override
    public Fitness getModel() {
        return fitness;
    }
}
